﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using TimeToGo.Infrastructure;
using TimeToGo.Presentation.Views;
using TimeToGo.Repositories;

namespace TimeToGo.Presentation.ViewModels
{
    internal class TimesViewModel
    {
        public SimpleDelegateCommand<object> OkCommand { get; set; }
        public SimpleDelegateCommand<object> CancelCommand { get; set; }
        public SimpleDelegateCommand<object> AddCommand { get; set; }
        public SimpleDelegateCommand<object> RemoveCommand { get; set; }
        public ObservableCollection<TimeInfo> Times { get; set; }
 
        private ITimesView _view;
        private IRepository<TimeInfo> _timeRepository;
        private UnitOfWork<TimeInfo> _unitOfWork;

        public TimesViewModel(ITimesView view, IRepository<TimeInfo> timeRepository)
        {
            _view = view;
            _timeRepository = timeRepository;
            _unitOfWork = new UnitOfWork<TimeInfo>(_timeRepository);

            Times = new ObservableCollection<TimeInfo>(_timeRepository.FindAll());

            OkCommand = new SimpleDelegateCommand<object>(Ok);
            CancelCommand = new SimpleDelegateCommand<object>(Cancel);
            AddCommand = new SimpleDelegateCommand<object>(Add);
            RemoveCommand = new SimpleDelegateCommand<object>(Remove);
        }

        private void Ok(object parameter)
        {
            // need to process the unit of work...
            _unitOfWork.Process();
            _view.Close();
        }

        private void Cancel(object parameter)
        {
            _view.Close();
        }

        private void Add(object parameter)
        {
            TimeInfo timeInfo = new TimeInfo { Name = "[new name]", Time = DateTime.Now };
            IView editView = new EditTimeView(timeInfo, Times);
            editView.ShowDialog();
            if (timeInfo.Name != null)
            {
                _unitOfWork.Add(timeInfo);
                Times.Add(timeInfo);
            }
        }

        private void Remove(object parameter)
        {
            TimeInfo ti = _view.SelectedTime;

            if (ti != null)
            {
                _unitOfWork.Remove(ti);
                Times.Remove(ti);
            }
        }

        public void ModifyTime(TimeInfo timeInfo)
        {
            IView editView = new EditTimeView(timeInfo, Times);
            editView.ShowDialog();
            if (timeInfo.Name != null)
            {
                _unitOfWork.Modify(timeInfo);
                Times.Add(timeInfo);
            }
        }
    }
}
